package service

import (
	"fmt"
	"im/model/chat"
	"im/model/request"
)

func Run(h *chat.Hub) {
	for {
		select {
		case client := <-h.Register:
			// 用户上线
			h.Clients[client.UserId] = client
			fmt.Println("用户上线")
		case client := <-h.Unregister:
			// 用户下线
			// h.Clients[client] = false
			delete(h.Clients, client.UserId)
			fmt.Println("用户下线")
		case message := <-h.Boardcast:
			// 消息广播
			fmt.Println("-------广播：")
			for _, client := range h.Clients {
				// 发送消息
				client.Send <- message
			}
		case messageReq := <-h.PrivateChat:
			// 私聊
			targetUserId := messageReq.TargeUserId
			fmt.Println("------私聊对象Id: ", targetUserId)
			if client := h.Clients[targetUserId]; client != nil {
				fmt.Println("------私聊对象: ", client)
				client.Send <- []byte(messageReq.Content)
			}
		case messageReq := <-h.GroupChat:
			// 群聊：不能给自己再发消息
			groupId := messageReq.GroupId
			sendUserId := messageReq.FromUserId
			fmt.Println("------群聊id: ", groupId)
			// 1. 在线：获取群成员信息
			cgms := AppService.ChatGroupMemberService
			if gms, err := cgms.GetGroupMembers(request.ChatGroupMemberReq{
				GroupId: groupId}); err != nil {
				// 获取群成员失败
			} else {
				// 2. 在线：给群成员发送消息
				for _, member := range gms {
					userId := member.UserId
					fmt.Printf("userId: %v, sendUserId: %v\n", userId, sendUserId)
					if userId != sendUserId {
						if client := h.Clients[userId]; client != nil {
							client.Send <- []byte(messageReq.Content)
						}
					}
				}
			}
		}
	}
}
